package com.hdjk.view.activity.personalcenter;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.adapter.RedeemDetailAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.dialog.MyAlertDialog;
import com.hdjk.view.entity.HoldingFundEntity;
import com.hdjk.view.network.PersonalNetWork;
import com.hdjk.view.util.StringAppUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.component.ListView.ListViewForScrollView;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/11/21.
 */

public class RedeemDetailActivity extends BaseActivity implements View.OnClickListener {

    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private TextView tv_total, tv_time, tv_yesterday, tv_sum, tv_sum_pre, tv_cost, tv_intransit, tv_sum1, tv_cash, tv_detail, tv_redeem;
    private ImageView img_yesterday, img_sum;
    private ListViewForScrollView lv_data_list;
    private RedeemDetailAdapter mAdapter;
    private Resources resources;

    private List<HoldingFundEntity> funds;
    private String title, portfolioId, fundCode, type, total;
    private boolean sellEnable = true;
    private boolean canSell = true;
    private BigDecimal bdHoldingAssets = BigDecimal.ZERO;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_redeem_detail);
        resources = getResources();
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        tv_total = (TextView) findViewById(R.id.tv_total);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_yesterday = (TextView) findViewById(R.id.tv_yesterday);
        tv_sum = (TextView) findViewById(R.id.tv_sum);
        tv_sum_pre = (TextView) findViewById(R.id.tv_sum_pre);
        tv_cost = (TextView) findViewById(R.id.tv_cost);
        tv_intransit = (TextView) findViewById(R.id.tv_intransit);
        tv_sum1 = (TextView) findViewById(R.id.tv_sum1);
        tv_cash = (TextView) findViewById(R.id.tv_cash);
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        tv_redeem = (TextView) findViewById(R.id.tv_redeem);
        tv_redeem.setOnClickListener(this);

        img_yesterday = (ImageView) findViewById(R.id.img_yesterday);
        img_sum = (ImageView) findViewById(R.id.img_sum);

        lv_data_list = (ListViewForScrollView) findViewById(R.id.lv_data_list);
    }

    @Override
    protected void initData() {
        mDialog.show();
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        ((TextView) ttb_title_bar.findViewById(R.id.tvNavTitle)).setText(title);
        portfolioId = intent.getStringExtra("portfolioId");
        fundCode = intent.getStringExtra("fundCode");
        type = intent.getStringExtra("type");

        funds = new ArrayList<>();
        getHoldingFunds();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tv_redeem:
                if (bdHoldingAssets.compareTo(new BigDecimal("0.00")) > 0 && canSell) {
                    MyAlertDialog alertDialog = new MyAlertDialog(RedeemDetailActivity.this, "您将使用奕丰金融提供的基金销售服务", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(RedeemDetailActivity.this, RedeemConfirmActivity.class);
                            intent.putExtra("title", title);
                            intent.putExtra("type", type);
                            intent.putExtra("portfolioId", portfolioId);
                            intent.putExtra("fundCode", fundCode);
                            intent.putExtra("money", StringAppUtil.formatDecimal(bdHoldingAssets.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2));
                            intent.putExtra("funds", (Serializable) funds);

                            startActivityForResult(intent, 1001);
                        }
                    });
                    alertDialog.show();
                } else {
                    ToastUtils.showShortToast(this, "没有可赎回的份额");
                }
                break;
        }
    }

    private void getHoldingFunds() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(this));
            if (type.equals("0") || type.equals("1")) {
                obj.put("fundCode", fundCode);
                obj.put("portfolioId", portfolioId);
            } else {
                obj.put("portfolioId", portfolioId);
            }

            PersonalNetWork.getHoldingFundDetail(UserTokenUtil.getToken(this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof List) {
                        funds = (List<HoldingFundEntity>) msg.getData();
                        BigDecimal bdTotal = BigDecimal.ZERO;
                        BigDecimal bdYesterday = BigDecimal.ZERO;
                        BigDecimal bdSum = BigDecimal.ZERO;
                        BigDecimal bdInvestmentAmount = BigDecimal.ZERO;
                        BigDecimal bdIntransitAssets = BigDecimal.ZERO;
                        BigDecimal bdDividendCash = BigDecimal.ZERO;
                        for (HoldingFundEntity fund : funds) {
                            if (fund.getSellEnable().equals("N"))
                                sellEnable = false;

                            String value = fund.getCurrentValue();
                            if (null != value && !"".equals(value)) {
                                BigDecimal b = new BigDecimal(value);
                                bdTotal = bdTotal.add(b);
                            }

                            String previousProfitNLoss = fund.getPreviousProfitNLoss();
                            if (null != previousProfitNLoss && !"".equals(previousProfitNLoss)) {
                                BigDecimal b = new BigDecimal(previousProfitNLoss);
                                bdYesterday = bdYesterday.add(b);
                            }

                            String profitLoss = fund.getProfitNLoss();
                            if (null != profitLoss && !"".equals(profitLoss)) {
                                BigDecimal b = new BigDecimal(profitLoss);
                                bdSum = bdSum.add(b);
                            }

                            String investmentAmount = fund.getInvestmentAmount();
                            if (null != investmentAmount && !"".equals(investmentAmount)) {
                                BigDecimal b = new BigDecimal(investmentAmount);
                                bdInvestmentAmount = bdInvestmentAmount.add(b);
                            }

                            String intransitAssets = fund.getIntransitAssets();
                            if (null != intransitAssets && !"".equals(intransitAssets)) {
                                BigDecimal b = new BigDecimal(intransitAssets);
                                bdIntransitAssets = bdIntransitAssets.add(b);
                            }

                            String dividendCash = fund.getDividendCash();
                            if (null != dividendCash && !"".equals(dividendCash)) {
                                BigDecimal b = new BigDecimal(dividendCash);
                                bdDividendCash = bdDividendCash.add(b);
                            }

                            String availableUnit = fund.getAvailableUnit();
                            String nav = fund.getNav();
                            if ((null != availableUnit && !"".equals(availableUnit)) && (null != nav && !"".equals(nav))) {
                                BigDecimal b = new BigDecimal(availableUnit);
                                if (b.compareTo(new BigDecimal("0.00")) < 1) {
                                    canSell = false;
                                }
                                BigDecimal c = new BigDecimal(nav);
                                bdHoldingAssets = bdHoldingAssets.add(b.multiply(c).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                        }
//                        if (!funds.get(0).getNavDate().equals("")) {
//                            String date = DateUtil.formatDate(Long.parseLong(funds.get(0).getNavDate()), "yyyy-MM-dd");
//                            tv_time.setText(date);
//                        } else {
//                            String date = DateUtil.formatDate(new Date().getTime(), "yyyy-MM-dd");
//                            tv_time.setText(date);
//                        }

                        total = StringAppUtil.formatDecimal(bdTotal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2);
                        tv_total.setText(total);
                        tv_yesterday.setText(StringAppUtil.formatDecimal(bdYesterday.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2));
                        tv_sum.setText(StringAppUtil.formatDecimal(bdSum.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2));
                        tv_cost.setText(StringAppUtil.formatDecimal(bdInvestmentAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2) + "元");
                        tv_intransit.setText(StringAppUtil.formatDecimal(bdIntransitAssets.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2) + "元");
                        tv_sum1.setText(StringAppUtil.formatDecimal(bdSum.subtract(bdDividendCash).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2) + "元");
                        tv_cash.setText(StringAppUtil.formatDecimal(bdDividendCash.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(), 2) + "元");

                        if (sellEnable) {
                            tv_redeem.setVisibility(View.VISIBLE);
                        } else {
                            tv_redeem.setVisibility(View.GONE);
                        }
                        if (bdYesterday.compareTo(BigDecimal.ZERO) > 0)
                            img_yesterday.setImageResource(R.drawable.up);
                        else if (bdYesterday.compareTo(BigDecimal.ZERO) < 0)
                            img_yesterday.setImageResource(R.drawable.down);

                        if (bdSum.compareTo(BigDecimal.ZERO) > 0)
                            img_sum.setImageResource(R.drawable.up);
                        else if (bdSum.compareTo(BigDecimal.ZERO) < 0)
                            img_sum.setImageResource(R.drawable.down);
                        if (mAdapter == null) {
                            mAdapter = new RedeemDetailAdapter(RedeemDetailActivity.this, total);
                            mAdapter.setDataList(funds);
                            lv_data_list.setAdapter(mAdapter);
                        } else {
                            mAdapter.setDataList(funds);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1002) {
            back();
        }
    }
}